<template>
  <div>
    <!-- 面包屑导航区 -->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>商品管理</el-breadcrumb-item>
      <el-breadcrumb-item>商品分类</el-breadcrumb-item>
    </el-breadcrumb>

    <!-- 卡片视图区 -->
    <el-card>
      <el-row>
        <el-col>
          <el-button type="primary" @click="showaddCart">添加分类</el-button>
        </el-col>
      </el-row>

      <!-- 表格 -->
      <tree-table
        :data="GoodsList"
        :columns="columns"
        :selection-type="false"
        :expand-type="false"
        border
        show-index
        index-text="#"
        :show-row-hover="false"
      >
        <!-- //是否有效 -->
        <template slot="isok" slot-scope="scope">
          <i
            class="el-icon-error"
            style="color: red"
            v-if="scope.row.cat_deleted === true"
          ></i>
          <i class="el-icon-success" style="color: lightgreen" v-else></i>
        </template>
        <!-- 排序 -->
        <template slot="order" slot-scope="scope">
          <el-tag size="mini" v-if="scope.row.cat_level === 0">一级</el-tag>
          <el-tag
            size="mini"
            type="success"
            v-else-if="scope.row.cat_level === 1"
            >二级</el-tag
          >
          <el-tag size="mini" type="warning" v-else>三级</el-tag>
        </template>
        <!-- 操作 -->
        <template slot="opt" slot-scope="scope">
          <el-button  @click="showEditDialog(scope.row.cat_id)" type="primary" icon="el-icon-edit" size="mini"
            >编辑</el-button
          >
          <el-button  @click="open(scope.row.cat_id)" type="danger" icon="el-icon-delete" size="mini"
            >删除</el-button
          >
        </template>
      </tree-table>
      <!-- 页码 -->
      <!-- 页码区域 -->
      <el-pagination
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="queryInfo.pagenum"
        :page-sizes="[1, 2, 5, 10]"
        :page-size="queryInfo.pagesize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
      >
      </el-pagination>
    </el-card>

    <!-- 添加分类对话框 -->
    <el-dialog
      @close="addCateDialog"
      title="添加分类"
      :visible.sync="dialogVisible"
      width="50%"
    >
      <!-- 内容主题区 -->
      <el-form
        :model="addForm"
        ref="addFormRef"
        :rules="addFormRules"
        label-width="100px"
      >
        <el-form-item label="分类名称" prop="cat_name">
          <el-input v-model="addForm.cat_name"></el-input>
        </el-form-item>
        <el-form-item label="父级分类">
          <!-- 级联选择器 -->
          <el-cascader
            change-on-select
            clearable
            expand-trigger="hover"
            v-model="selectedKeys"
            :options="ParentCateList"
            :props="cascaderProps"
            @change="handleChange"
          ></el-cascader>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="addCart">确 定</el-button>
      </span>
    </el-dialog>

      <!-- 编辑分类对话框 -->
    <el-dialog title="修改角色信息" :visible.sync="dialogVisible1" width="50%"
    @close="editDialogClosed">
      <!-- 内容主题区 -->
      <el-form
        :model="editForm"
        :rules="editFormRules"
        ref="editFormRef"
        label-width="100px"
      >
        <el-form-item label="角色名称" prop="cat_name">
          <el-input v-model="editForm.cat_name"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible1 = false">取 消</el-button>
        <el-button type="primary" @click="editUserInfo"
          >确 定</el-button
        >
      </span>
    </el-dialog>
  </div>
</template>
<script>
export default {
  data() {
    return {
      //选中的父级分类id数组
      selectedKeys: [],
      cascaderProps: {
        value: "cat_id",
        label: "cat_name",
        children: "children",
      },
      dialogVisible: false,
       dialogVisible1: false,
      GoodsList: [],
      //获取商品列表的参数对象  查询条件
      queryInfo: {
        type: 3,
        //当前页数
        pagenum: 1,
        //当前每页显示多少 条数据
        pagesize: 5,
      },
      //总数居条数
      total: 0,
      //为table指定列的定义
      columns: [
        {
          label: "分类名称",
          prop: "cat_name",
        },
        {
          label: "是否有效",
          //表示将当前列定义为模板列
          type: "template",
          //表示当前这一列使用模板名称
          template: "isok",
        },
        {
          label: "排序",
          //表示将当前列定义为模板列
          type: "template",
          //表示当前这一列使用模板名称
          template: "order",
        },
        {
          label: "操作",
          //表示将当前列定义为模板列
          type: "template",
          //表示当前这一列使用模板名称
          template: "opt",
        },
      ],
      //添加分类表单
      addForm: {
        cat_name: "",
        //父级分类id
        cat_pid: 0,
        //分类等级，默认添加1级分类
        cat_level: 0,
      },
      //添加分类表单规则对象
      addFormRules: {
        cat_name: [
          { required: true, message: "请输入分类名称", trigger: "blur" },
          {
            min: 2,
            max: 10,
            message: "长度在 2 到 10 个字符",
            trigger: "blur",
          },
        ],
      },
      //父级分类列表
      ParentCateList: [],
           //编辑分类对象
      editForm:{},
        //修改分类表单规则对象
       editFormRules:{
         cat_name:[
           { required: true, message: "请输入用户名", trigger: "blur" },
          {
            min: 2,
            max: 10,
            message: "长度在 2 到 10 个字符",
            trigger: "blur",
          },
        ],
       },
    };
  },
  created() {
    this.getGoodsList();
  },
  methods: {
    //请求商品分类
    async getGoodsList() {
      const { data: res } = await this.$http.get("categories", {
        params: this.queryInfo,
      });
      if (res.meta.status !== 200) {
        return this.$message.error("获取商品列表失败！");
      }
      this.GoodsList = res.data.result;
      this.total = res.data.total;
      console.log(res.data);
    },
    //监听pagesize 改变的事件
    handleSizeChange(newSize) {
      console.log(newSize);
      this.queryInfo.pagesize = newSize;
      this.getGoodsList();
    },
    //点击切换页数 改变的事件
    handleCurrentChange(newPage) {
      console.log(newPage);
      this.queryInfo.pagenum = newPage;
      this.getGoodsList();
    },
    //点击展开添加分类对话框
    showaddCart() {
      this.getParentCate();
      this.dialogVisible = true;
    },

    //获取父级分类的列表
    async getParentCate() {
      const { data: res } = await this.$http.get("categories", {
        params: {
          type: 2,
        },
      });
      if (res.meta.status !== 200) {
        return this.$message.error("获取角色列表失败！");
      }
      console.log(res.data);
      this.ParentCateList = res.data;
    },
    //下拉选择分类
    handleChange(value) {
      // console.log(value);
      if (this.selectedKeys.length > 0) {
        this.addForm.cat_pid = this.selectedKeys[this.selectedKeys.length - 1];
        this.addForm.cat_level = this.selectedKeys.length;
      } else {
        this.addForm.cat_pid = 0;
        this.addForm.cat_level = 0;
      }
    },
    //点击按钮添加新的分类
    addCart() {
      this.$refs.addFormRef.validate(async (value) => {
        if (!value) return;
        const { data: res } = await this.$http.post("categories", this.addForm);
        if (res.meta.status !== 201) {
          return this.$message.error(res.meta.msg);
        }
        this.$message.success("添加分类成功");
        this.getGoodsList();
        this.dialogVisible = false;
      });
    },
    //监听添加分类对话框关闭
    addCateDialog() {
      this.$refs.addFormRef.resetFields();
      this.selectedKeys = [];
      this.addForm.cat_pid = 0;
      this.addForm.cat_level = 0;
    },
         //展示编辑角色对话框
    async showEditDialog(id){
      console.log(id);
      const {data:res} = await this.$http.get('categories/'+ id)
         if(res.meta.status !== 200){
           return this.$message.error(res.meta.msg);
         } 
        this.editForm = res.data
        console.log(res.data);
      this.dialogVisible1 = true
    },

      editUserInfo(){
      this.$refs.editFormRef.validate(async value=>{
        if(!value)return;
        //通过预校验则发起修改用户请求
         const {data:res} = await this.$http.put('categories/'+this.editForm.cat_id,{
           cat_name:this.editForm.cat_name,
         })
        if(res.meta.status !== 200) return this.$message.error(res.meta.msg);
       
       //关闭对话框
      this.dialogVisible1 = false;
      //刷新数据列表
      this.getGoodsList();
      this.$message.success('修改成功');
      })
      
    },
      //监听分类修改资料对话框的关闭事件
    editDialogClosed(){
       this.$refs.editFormRef.resetFields();
    },
     //删除分类提示
      open(id) {
        this.$confirm('此操作将永久该角色, 是否继续?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(async() => {
         const{data:res} = await this.$http.delete('categories/'+id)
          if(res.meta.status !== 200) {return this.$message.error(res.meta.msg)};
         console.log(res);
         //重新获取分类列表数据
         this.getGoodsList();
          this.$message({
            type: 'success',
            message: '删除成功!'
          });
        }).catch(() => {
          this.$message({
            type: 'info',
            message: '已取消删除'
          });          
        });
      },
  },
};
</script>
<style lang="scss" scoped>
.el-row {
  margin: 10px 0;
}
.el-cascader {
  width: 100%;
}
</style>
